package com.qingyun.form.base

import com.qingyun.form.internal.FormItemList
import com.qingyun.form.internal.render.FormRender
import com.qingyun.form.internal.render.IFormRender
import com.qingyun.form.items.BaseFormItem
import com.qingyun.form.validator.FormValidatorResult
import org.json.JSONObject

class FormGroup {
    /**
     * 表单项列表
     */
    private val items = FormItemList()

    /** Title布局的最大宽度,在布局管理器中计算 */
    internal var maxTitleWidth: Int = -1

    /** 表单渲染接口 */
    private var render: IFormRender? = null

    /**
     * 获取表单项数量
     */
    val itemCount: Int
        get() = items.size
    var viewonly: Boolean = false
        set(value){
            field = value
            items.forEach { it.viewOnly = value }
            refresh()
        }

    private fun refresh() {
        this.render?.onNeedRefresh()
    }

    internal fun attachRender(render: FormRender) {
        this.render = render
    }

    fun addItem(item: BaseFormItem): Boolean {
        return addItem(-1, item)
    }

    fun addItem(index: Int, item: BaseFormItem): Boolean {
        return items.add(index, item).also {
            if (!it) {
                return false
            }
            val indexOf = indexOf(item)
            item.onFormItemAdd(indexOf, this)
            render?.onFormItemInserted(item, indexOf)
        }
    }

    fun addChildren(parent: BaseFormItem, child: BaseFormItem): Boolean {
        val index = items.findChildrenIndex(parent)
        if (index < 0) {
            return false
        }
        child.parent = parent
        return items.add(index + 1, child)
    }

    operator fun get(position: Int): BaseFormItem {
        return items[position]
    }

    operator fun get(name: String): BaseFormItem? {
        return items[name]
    }

    fun indexOf(item: BaseFormItem): Int {
        return items.indexOf(item)
    }

    fun destroy() {
        items.forEach { it.onFormItemRemoved() }
        items.destroy()
    }

    fun refreshItem(item: BaseFormItem) {
        this.render?.onFormItemUpdated(indexOf(item))
    }

    fun validateForm(highlight: Boolean = true): FormValidatorResult {
        items.forEach {
            val itemResult = it.mValidator?.validate(it, it.value)
            if (itemResult?.successfully() == false) {
                if (highlight) {
                    this.render?.highlight(itemResult.item)
                }
                return itemResult
            }
        }
        return FormValidatorResult.success()
    }

    fun toJson(): String {
        val obj = JSONObject()
        items.forEach {
            val name = it.name
            val value = it.value
            obj.put(name, value?:"")
        }
        obj.toString()
        return obj.toString()
    }


}